package com.zzzzzz.account.settings;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.shiro.authc.credential.PasswordService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zzzzzz.account.signin.NoSuchOnlineUserException;
import com.zzzzzz.account.signin.OnlineService;
import com.zzzzzz.account.signin.UserPasswordException;
import com.zzzzzz.account.user.User;
import com.zzzzzz.account.user.UserDao;

@Service("settingsService")
public class SettingsServiceImpl implements SettingsService {
	
	@Resource
	private OnlineService onlineService;
	@Resource
	private PasswordService passwordService;
	@Resource
	private ProfilePictureService profilePictureService;
	@Resource
	private UserDao userDao;
	
	public void editPortrait(EditPortraitForm editPortraitForm) throws NoSuchOnlineUserException, IOException {
		Long userId = onlineService.findUserId();
		CommonsMultipartFile files = editPortraitForm.getFiles();
		profilePictureService.saveProfilePicture(userId, files.getBytes());
	}
	
	public void editPassword(String curPassword, String newPassword) throws NoSuchOnlineUserException, UserPasswordException {
		User user = onlineService.findUser();
		if(!passwordService.passwordsMatch(curPassword, user.getPassword())) {
			throw new UserPasswordException(UserPasswordException.PASSWORDS_WRONG);
		}
		
		userDao.editPassword(user.getId(), newPassword);
	}
	
	public void editEmail(String curPassword, String email) throws NoSuchOnlineUserException, UserPasswordException {
		User user = onlineService.findUser();
		if(!passwordService.passwordsMatch(curPassword, user.getPassword())) {
			throw new UserPasswordException(UserPasswordException.PASSWORDS_WRONG);
		}
		
		userDao.editEmail(user.getId(), user.getEmail());
	}
	
}
